package com.zy.nft_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.nft_system.domain.*;
import com.zy.nft_system.domain.dto.OrderDto;
import com.zy.nft_system.exception.MyException;
import com.zy.nft_system.mapper.*;
import com.zy.nft_system.service.OrderService;
import com.zy.nft_system.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
* @author 这是那头猪？
* @description 针对表【t_order(订单表)】的数据库操作Service实现
* @createDate 2022-12-10 14:47:09
*/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @Resource
    OrderMapper orderMapper;

    @Resource
    AccountMapper accountMapper;

    @Resource
    UserantiqueMapper userantiqueMapper;

    @Resource
    AntiqueMapper antiqueMapper;

    @Resource
    QntiqueauthMapper qntiqueauthMapper;

    @Resource
    UserMapper  userMapper;

    @Override
    public Result insertShopChe(Order order) {
        log.info("正在查询订单");
        Order order1 = orderMapper.selectOne(new QueryWrapper<Order>().eq("uid", order.getUid()).eq("antiqueInfo", order.getAntiqueinfo()).eq("status", 0));
        if (order1 == null) {
            log.info("正在初始化购物车");
            order.setStatus(0);
            order.setNumber(1);
            int insert = orderMapper.insert(order);
            if (insert != 1) {
                log.info("初始化失败");
                return Result.error("网络拥挤，添加购物车失败");
            }else {
                log.info("初始化成功");
                return Result.success("添加购物车成功", null);
            }
        }
        log.info("购物车中有订单，现在只用修改数量和价格");
        order.setNumber(order1.getNumber()+1);
        order.setSell(order1.getSell()+order.getSell());
        order.setId(order1.getId());
        int i = orderMapper.updateById(order);
        if (i != 1) {
            log.info("添加购物车失败");
            return Result.error("网络拥挤，添加购物车失败");
        }
        return Result.success("添加购物车成功", null);
    }

    @Override
    @Transactional(rollbackFor = MyException.class,propagation = Propagation.REQUIRED)
    public Result goShop(Order order) {
        log.info("查看用户账户中钱是否到位");
        Account account = accountMapper.selectOne(new QueryWrapper<Account>().eq("uid", order.getUid()).ge("overage", order.getSell()*order.getNumber()));
        if (account == null) {
            log.info("账户金额不够");
            throw new MyException("账户金额不够,请重值之后再购买");
        }
        log.info("账户金额够正在收款");
        account.setModiftime(DateUtils.dataFormat(new Date()));
        account.setOverage(account.getOverage()-(order.getSell()*order.getNumber()));
        int update = accountMapper.update(account, new QueryWrapper<Account>().eq("uid", order.getUid()));
        if (update != 1) {
            log.info("收款失败");
            throw new MyException("网络原因收款失败");
        }
        log.info("收款成功");

        log.info("正在为购物车中添加订单");
        //设置订单状态
        order.setStatus(1);
        //设置发货时间
        order.setSendtime(DateUtils.dataFormat(new Date()));
        //设置订单id
        order.setOrderid(new Random().nextInt(999999));
        int insert = orderMapper.insert(order);
        if (insert != 1) {
            log.info("订单表添加数据失败");
            throw new MyException("网络原因购买失败");
        }
        log.info("生成订单成功");

        log.info("正在查看藏品剩余的数量");
        Antique antique1 = antiqueMapper.selectOne(new QueryWrapper<Antique>().eq("id", order.getAntiqueinfo()).ge("count", order.getNumber()));
        if (antique1 == null) {
            log.info("藏品数量不足");
            throw new MyException("藏品数量不足,请换个时间段购买");
        }
        log.info("仓库藏品充足");
        antique1.setCount(antique1.getCount()-order.getNumber());
        int update1 = antiqueMapper.update(antique1, new QueryWrapper<Antique>().eq("id", order.getAntiqueinfo()));
        if (update1 != 1) {
            log.info("出货失败");
            throw new MyException("网络原因购买失败");
        }
        log.info("出货成功");

        Antique antique = antiqueMapper.selectOne(new QueryWrapper<Antique>().eq("id", order.getAntiqueinfo()));
        Integer integer = userantiqueMapper.selectCount(new QueryWrapper<Userantique>().eq("aid", order.getAntiqueinfo()));
        if (integer == null) {
            integer = 0;
        }
        if (order.getNumber() > 1){
            //记录发货次数
            int cont=1;
            while (cont <= order.getNumber()){
                log.info("正在为用户发送藏品");
                Userantique userantique = new Userantique();
                userantique.setName(antique.getName());
                userantique.setNumber(integer+1);
                userantique.setPurchaseprice(order.getSell());
                userantique.setImgsrc(antique.getImgsrc());
                userantique.setUid(order.getUid());
                userantique.setAid(antique.getId());
                int insert1 = userantiqueMapper.insert(userantique);
                if (insert1 != 1) {
                    log.info("发送藏品失败");
                    throw new MyException("网络原因购买失败");
                }
                cont++;
                integer++;
            }
            log.info("藏品发送成功");
            log.info("购买成功");
            return Result.success("购买成功",null);
        }else {
            log.info("正在为用户发送藏品");
            Userantique userantique = new Userantique();
            userantique.setName(antique.getName());
            userantique.setNumber(integer+1);
            userantique.setPurchaseprice(order.getSell());
            userantique.setImgsrc(antique.getImgsrc());
            userantique.setUid(order.getUid());
            userantique.setAid(antique.getId());
            int insert1 = userantiqueMapper.insert(userantique);
            if (insert1 != 1) {
                log.info("发送藏品失败");
                throw new MyException("网络原因购买失败");
            }
            log.info("藏品发送成功");
            log.info("购买成功");
            return Result.success("购买成功",null);
        }
    }

    @Override
    public Result orderList(Order order) {
       List<OrderDto> orders = orderMapper.orderList(order);
        if (orders == null) {
            log.info("查询订单失败");
            return Result.error("查询订单失败");
        }
        log.info("查询订单成功");
        return Result.success("查询订单成功", orders);
    }

    @Override
    public Result listChe(String name, int uid) {
       List<OrderDto > orderDtos =orderMapper.listChe(name,uid);
        if (orderDtos.isEmpty()) {
            log.info("用户购物车为空");
            return Result.error("未找到该藏品");
        }
        log.info("查询用户购物车成功");
        return Result.success("查询用户购物车成功", orderDtos);
    }

    @Override
    public Result queryAll() {
        Integer userCount = userMapper.selectCount(null);
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<Order>().eq("status", 1).ge("createTime", DateUtils.dataFormat(new Date(new Date().getTime() - 86400000)));
        Integer orders = orderMapper.selectCount(orderQueryWrapper);
        List<Order> orders1 = orderMapper.selectList(orderQueryWrapper);
        Integer sells = 0;
        for (Order o: orders1) {
            sells+=o.getSell();
        }
        List<Qntiqueauth> qntiqueauths = qntiqueauthMapper.selectList(new QueryWrapper<Qntiqueauth>().eq("consignment", 1));
        Integer antiqueCount=qntiqueauths.size();
        Antique[] antiques = new Antique[antiqueCount];
        for (int i = 0; i < antiqueCount; i++) {
            Antique antique = antiqueMapper.selectOne((new QueryWrapper<Antique>().eq("id", qntiqueauths.get(i).getAid())));
            antiques[i]=antique;
        }
        log.info("查询成功");
        HashMap<String, Object> s = new HashMap<>();
        s.put("userCount", userCount);
        s.put("orders", orders);
        s.put("sells", sells);
        s.put("antiqueCount", antiqueCount);
        s.put("antiques", antiques);

        return Result.success("查询成功", s);
    }

    @Override
    public Result sellsAll() {
        int[] sells =new int[7];
        for (int i = 0; i < 7; i++) {
            QueryWrapper<Userantique> wrapper = new QueryWrapper<Userantique>().ge("createTime", DateUtils.dataFormat(new Date(new Date().getTime() - (86400000*(i+1)))));
            List<Userantique> userantiques = userantiqueMapper.selectList(wrapper);
            if (userantiques.isEmpty()) {
                sells[i]=0;
                continue;
            }
            for (Userantique u:userantiques) {
                sells[i]+=u.getPurchaseprice();
            }
            for (int j = 0; j < i; j++) {
                sells[i]=sells[i]-sells[j];
            }
        }
        log.info("查询成功");
        return Result.success("查询成功", sells);
    }
}




